<template>
  <div class="week-switcher">
    <img 
      src="@/assets/icon/icon_left_nor.png" 
      alt="上一周" 
      @click="prevWeek" 
      class="switch-button"
    >
    <span class="week-range">{{ weekRange }}</span>
    <img 
      src="@/assets/icon/icon_right_nor.png" 
      alt="下一周" 
      @click="nextWeek" 
      class="switch-button"
    >
    <span v-if="!isCurrentWeek" class="current-week-tag" @click="weekOffset = 0">本周</span>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'

// 当前周偏移量（相对于当前周）
const weekOffset = ref<number>(0)
const time = ref<{
  startDate: any,
  endDate: any
}>({
  startDate: '',
  endDate: ''
})
// 计算当前周的开始日期和结束日期
const weekRange = computed<string>(() => {
  const { startDate, endDate } = getCurrentWeekRange(weekOffset.value)

  if(weekOffset.value === 0){
    time.value = {
      startDate: formatDate(startDate),
      endDate: formatDate(endDate)
    }
  }
  return `${formatDate(startDate)} ~ ${formatDate(endDate)}`
})

// 检查是否是当前周
const isCurrentWeek = computed<boolean>(() => {
  return weekOffset.value === 0
})
const emits = defineEmits(['timeSwitch']);

// 获取指定偏移量的周范围
function getCurrentWeekRange(offset: number): { startDate: Date, endDate: Date } {
  const now = new Date()
  const dayOfWeek = (now.getDay() + 6) % 7 // 周一为一周开始 (0=周一, 6=周日)
  const startDate = new Date(now)
  startDate.setDate(now.getDate() - dayOfWeek + offset * 7)
  startDate.setHours(0, 0, 0, 0)
  
  const endDate = new Date(startDate)
  endDate.setDate(startDate.getDate() + 6)
  endDate.setHours(23, 59, 59, 999)
  emits('timeSwitch', { startDate, endDate });
  return { startDate, endDate }
}

// 格式化日期为 YYYY-MM-DD
function formatDate(date: Date): string {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 切换到上一周
function prevWeek(): void {
  weekOffset.value--
}

// 切换到下一周
function nextWeek(): void {
  weekOffset.value++
}
</script>

<style scoped>
.week-switcher {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  font-size: 18px;
}

.switch-button {
  cursor: pointer;
  width: 30px;
  height: 30px;
}



.week-range {
  min-width: 220px;
  text-align: center;
  font-weight: 400;
  color: #000;
  font-size: 16px;
}

.current-week-tag {
  width: 40px;
  height: 24px;
  border-radius: 3px 3px 3px 3px;
  cursor: pointer;
  border: 1px solid #DCDCDC;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  color: rgba(0,0,0,0.9);
}
</style>